package spynx.desl.runtime.operators.impl;

import spynx.desl.runtime.IExecutionContext;
import spynx.desl.runtime.IOperator;
import spynx.util.InvalidOperation;

public class BooleanOperator implements IOperator {

	@Override
	public String getOperator() {
		return "BoolOp";
	}

	@Override
	public Object apply(IExecutionContext context, String operator,
			Object... args) {
		Object left = context.resolveValue(args[0]);
		Object right = null;
		if (!(left instanceof Boolean))
			throw new InvalidOperation(operator, left);
		if ("&&".equals(operator)) { 
			if ((Boolean)left) { 
				right = context.resolveValue(args[1]);
				if (!(right instanceof Boolean))
					throw new InvalidOperation(operator, left, right);
				return right;
			}
			else
				return left;
		}
		if ("||".equals(operator)) {
			if ((Boolean)left)
				return left;
			right = context.resolveValue(args[1]);
			if (!(right instanceof Boolean))
				throw new InvalidOperation(operator, left, right);
			return right;
		}
		return null;
	}

}
